package com.example.psychologicalappointmentsystem.handler;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.example.psychologicalappointmentsystem.Entity.User;
import com.example.psychologicalappointmentsystem.Enum.UserRole;
import com.example.psychologicalappointmentsystem.JpaRepository.UserRepository;
import com.example.psychologicalappointmentsystem.Object.ChatMessageVO;
import com.example.psychologicalappointmentsystem.service.ChatMessageService;
import com.example.psychologicalappointmentsystem.service.QuestionnaireService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ClassName ChatWebSocketHandler
 * Description TODO 聊天功能
 * Date 2025/2/17 14:48
 * Version 1.0
 */
@Component
@Slf4j
public class ChatWebSocketHandler extends TextWebSocketHandler {
    // 使用 ConcurrentHashMap 存储用户与会话之间的映射
    private final ConcurrentHashMap<String, WebSocketSession> sessions = new ConcurrentHashMap<>();

    @Autowired
    QuestionnaireService questionnaireService;

    @Autowired
    UserRepository userRepository;

    @Autowired
    ChatMessageService chatMessageService;

    //建立链接的时候调用
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 假设每个连接都有一个唯一的标识符（例如用户名），用于识别用户
        String userId = getUserId(session);
        if (userId != null) {
            sessions.put(userId, session);
        }
    }

    //接受发送来的消息
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) {
        try {
            //并解析成对象
            ChatMessageVO chatMessageVO = parseReceiverMessage(message.getPayload());

            //先判断，用户是否存在
            Optional<User> userDOOptional = userRepository.findById(Long.parseLong(getUserId(session)));
            User userDO = null;
            if (userDOOptional.isPresent()){
                userDO = userDOOptional.get();
            }else {
                session.sendMessage(new TextMessage("用户不存在,请创建用户"));
                throw new Exception("用户不存在,请创建用户");
            }

            //获取接受消息对象
            WebSocketSession receiverSession = sessions.get(chatMessageVO.getReceiverId().toString());

            //给消息来源返回数据
            ChatMessageVO chatMessageSourceVO = new ChatMessageVO();
            //客户需要返回情绪，发送者是否是客户
            if (userDO.getRole().toString().equals(UserRole.VISITOR.name())){
                //调用情感分析模块
                String analyResult = questionnaireService.analyzeSentiment(chatMessageVO.getContent());
                //用户给的数据需要将情绪入库
                chatMessageVO.setEmotion(analyResult);
            }
            //保存聊天记录
            chatMessageService.saveMessage(chatMessageVO);

            //发送消息
            if (receiverSession != null && receiverSession.isOpen()) {
                receiverSession.sendMessage(new TextMessage(chatMessageVO.getContent()));
//                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(chatMessageSourceVO)));
            } else {
                chatMessageSourceVO.setResultContent("用户不在线");
                session.sendMessage(new TextMessage(JSONUtil.toJsonStr(chatMessageSourceVO)));
            }

        }catch (Exception e){
            log.error("发送消息失败！" + e.getMessage(), e);
        }

    }

    //链接关闭调用
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String userId = (String) session.getAttributes().get("userId");
        if (userId != null) {
            sessions.remove(userId);
        }
    }


    //将前端发送回来的消息解析成对象
    private ChatMessageVO parseReceiverMessage(String payload) {
        JSONObject payJson = JSONUtil.parseObj(payload);
        ChatMessageVO chatMessageVO = JSONUtil.toBean(payJson,ChatMessageVO.class);
        return chatMessageVO;
    }

    //从请求中获取用户id
    private String getUserId(WebSocketSession session){
        return session.getUri().getQuery().split("=")[1];
    }

}
